#include "UserManager.h"
#include "DatabaseManager.h"
#include <sstream> // 包含 std::istringstream
#include <iostream>
#include <stdexcept>

//全局变量时间戳
std::chrono::system_clock::time_point lastActivityTimestamp = std::chrono::system_clock::now();
using namespace std;
// 定义静态常量
const int UserManager::MAX_LOGIN_ATTEMPTS = 3;
const int UserManager::LOCKOUT_DURATION = 30;

// 静态实例初始化
UserManager& UserManager::getInstance() {
    static UserManager instance;
    return instance;
}

// 字符串转整数函数
int stringToInt(const std::string& str) {
    int result = 0;
    std::istringstream iss(str);
    iss >> result; // 从字符串中提取整数
    return result;
}

// 构造函数
UserManager::UserManager() {

	if (globalLoginAttempts >= MAX_LOGIN_ATTEMPTS) {
    isLocked = true; // 锁定系统
    globalLockoutTime = std::chrono::system_clock::now(); // 设置锁定时间
    cerr << "错误：系统已被锁定，请 " << LOCKOUT_DURATION << " 秒后重试。" << endl;
}
    // 从数据库加载用户到内存
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    string query = "SELECT * FROM users;";
    auto results = dbManager.fetchResults(query);
    for (const auto& row : results) {
        // 确保 row 是 std::vector<std::string>
        int id = stringToInt(row[0]); // row[0] 是 std::string
        string username = row[1]; // row[1] 是 std::string
        string passwordHash = row[2]; // row[2] 是 std::string
        User::Role role = User::stringToRole(row[3]);
        users.emplace(id, User(id, username, passwordHash, role));
    }
}


int UserManager::generateNewUserId() {
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    std::string query = "SELECT MAX(id) FROM users;";
    auto results = dbManager.fetchResults(query);

    int maxId = 0;
    if (!results.empty() && !results[0][0].empty()) {
        maxId = std::stoi(results[0][0]);
    }

    return maxId + 1;
}

// UserManager.cpp 中注册用户时的哈希函数
string hashPassword(const std::string& password) {
    return UserManager::getInstance().simpleHash(password);
}

void UserManager::recordLogin(int userId, const std::string& ipAddress) {
    sessions[userId] = SessionInfo(ipAddress);
    std::cout << "User " << userId << " logged in from " << ipAddress << std::endl;
}

//void UserManager::updateActivityTime(int userId) {
//    if (this->sessions.find(userId) != this->sessions.end()) {
//       this->sessions[userId].lastActivityTime = std::chrono::system_clock::now();
//        std::cout << "[DEBUG] 更新后的 lastActivityTime 为: " 
//                  << std::chrono::duration_cast<std::chrono::seconds>(
//                         this->sessions[userId].lastActivityTime.time_since_epoch()).count()
//                  << " 秒" << std::endl;
//    } else {
//        std::cout << "[DEBUG] 更新失败：用户 " << userId << " 不存在于会话列表中" << std::endl;
//    }
//}

// 用户操作时更新最后活动时间
void UserManager::updateActivityTime(int userId) {
    if (sessions.find(userId) != sessions.end()) {
        // 更新会话的最后活动时间为全局时间戳
        sessions[userId].lastActivityTime = lastActivityTimestamp;
        std::cout << "[DEBUG] 最后活动时间戳为: " 
                  << std::chrono::duration_cast<std::chrono::seconds>(lastActivityTimestamp.time_since_epoch()).count()
                  << " 秒" << std::endl;
    } else {
        std::cout << "[DEBUG] 更新失败：用户 " << userId << " 不存在于会话列表中" << std::endl;
    }
}

bool UserManager::isSessionExpired(int userId) {
    if (sessions.find(userId) != sessions.end()) {
        auto now = std::chrono::system_clock::now();

        // 输出 now 和 lastActivity 的时间戳，用于调试
        std::cout << "[DEBUG] 当前时间戳: " 
                  << std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count()
                  << " 秒" << std::endl;
        std::cout << "[DEBUG] 最后活动时间戳: " 
                  << std::chrono::duration_cast<std::chrono::seconds>(sessions[userId].lastActivityTime.time_since_epoch()).count()
                  << " 秒" << std::endl;

        auto duration = std::chrono::duration_cast<std::chrono::seconds>(
                            now - sessions[userId].lastActivityTime
                        ).count();

        std::cout << "[DEBUG] 用户 " << userId << " 会话检查 - 时长: " 
                  << duration << " 秒" << std::endl;
	lastActivityTimestamp = std::chrono::system_clock::now();

        if (duration > sessionTimeout.count()) {
            std::cout << "[DEBUG] 会话已过期，删除用户 " << userId << " 的会话" << std::endl;
            sessions.erase(userId);  
            return true;
        }
        return false;
    }

    std::cout << "[DEBUG] 用户 " << userId << " 无会话记录，视为过期" << std::endl;
    return true;
}


void UserManager::cleanExpiredSessions() {
    auto now = std::chrono::system_clock::now();
    for (auto it = sessions.begin(); it != sessions.end();) {
        auto duration = now - it->second.lastActivityTime;
        if (duration > sessionTimeout) {
            std::cout << "User " << it->first << " session expired." << std::endl;
            it = sessions.erase(it);
        } else {
            ++it;
        }
    }
}


// 用户注册
bool UserManager::registerUser(const string& username, const string& password, User::Role role) {
    // 检查内存中是否已存在该用户名
    for (const auto& pair : users) {
        if (pair.second.getUsername() == username) {
            std::cerr << "错误:用户名已存在" << std::endl;
            return false;
        }
    }

    // 检查数据库中是否已存在该用户名
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    std::string query = "SELECT username FROM users WHERE username = '" + username + "';";
    auto results = dbManager.fetchResults(query);
    if (!results.empty()) {
        std::cerr << "错误:数据库中用户名已存在" << std::endl;
        return false;
    }

    // 生成新用户 ID
    int newId = generateNewUserId();
    std::string passwordHash = simpleHash(password);

    // 插入用户到数据库
	std::string insertQuery = "INSERT INTO users (id, username, password_hash, role) VALUES (" 
                          + std::to_string(newId) + ", '" + username + "', '" + passwordHash + "', '" 
                          + User::roleToString(role) + "');";
    if (dbManager.executeQuery(insertQuery)) {
        // 插入成功后，更新内存中的用户列表
        users.emplace(newId, User(newId, username, passwordHash, role));
        std::cout << "用户注册成功" << std::endl;
        return true;
    } else {
        std::cerr << "错误:用户注册失败" << std::endl;
        return false;
    }
}


bool UserManager::loginUser(const std::string& username, const std::string& password) {
    // 检查全局锁定状态
    if (isLocked) {
        auto now = std::chrono::system_clock::now();
        auto lockoutEnd = globalLockoutTime + std::chrono::seconds(LOCKOUT_DURATION);
        if (now < lockoutEnd) {
            cerr << "错误：系统已被锁定，请 " 
                 << std::chrono::duration_cast<std::chrono::seconds>(lockoutEnd - now).count()
                 << " 秒后重试。" << endl;
            return false; // 直接返回，不执行登录逻辑
        } else {
            // 锁定时间已过，重置全局登录尝试次数和锁定状态
            globalLoginAttempts = 0;
            isLocked = false;
        }
    }

    // 查找用户
    bool userFound = false;
    for (const auto& pair : users) {
        if (pair.second.getUsername() == username) {
            userFound = true;
            // 验证密码
            if (verifyPassword(password, pair.second.getPasswordHash())) {
                // 登录成功，重置全局登录尝试次数
                globalLoginAttempts = 0;

		// 获取用户 ID 并初始化 lastActivityTime
                User* user = getUserByUsername(username);
		int userId = (user) ? user->getId() : -1; 
                sessions.emplace(userId, SessionInfo(std::chrono::system_clock::now()));

                cout << "[DEBUG] 用户 " << userId << " 登录成功，活动时间初始化成功" << endl;

		sessions.emplace(userId, SessionInfo(std::chrono::system_clock::now()));
		cout << "[DEBUG] 初始化 lastActivityTime 为: " 
		     << std::chrono::duration_cast<std::chrono::seconds>(
			    sessions[userId].lastActivityTime.time_since_epoch()).count()
		     << " 秒" << endl;


                // 记录登录日志
                recordLogin(pair.first, "127.0.0.1"); // 假设 IP 地址为 127.0.0.1
                cout << "用户登录成功。用户 ID: " << pair.first << endl;
                return true;
            } else {
                // 密码错误，增加全局登录尝试次数
                globalLoginAttempts++;
                cerr << "错误：密码不正确。剩余尝试次数: " 
                     << (MAX_LOGIN_ATTEMPTS - globalLoginAttempts) << endl;

                // 检查是否达到最大尝试次数
                if (globalLoginAttempts >= MAX_LOGIN_ATTEMPTS) {
                    // 锁定全局登录功能
                    globalLockoutTime = std::chrono::system_clock::now();
                    isLocked = true;
                    cerr << "错误：系统已被锁定，请 " << LOCKOUT_DURATION << " 秒后重试。" << endl;
                }
                return false;
            }
        }
    }

    // 如果用户未找到，增加全局登录尝试次数
    if (!userFound) {
        globalLoginAttempts++;
        cerr << "错误：用户未找到。剩余尝试次数: " 
             << (MAX_LOGIN_ATTEMPTS - globalLoginAttempts) << endl;

        // 检查是否达到最大尝试次数
        if (globalLoginAttempts >= MAX_LOGIN_ATTEMPTS) {
            // 锁定全局登录功能
            globalLockoutTime = std::chrono::system_clock::now();
            isLocked = true;
            cerr << "错误：系统已被锁定，请 " << LOCKOUT_DURATION << " 秒后重试。" << endl;
        }
    }

    cerr << "错误：用户未找到。" << endl;
    return false;
}

// 用户注销
void UserManager::logoutUser(int userId) {
    if (sessions.find(userId) != sessions.end()) {
        sessions.erase(userId);
        cout << "用户注销成功，用户 ID: " << userId << endl;
    } else {
        cerr << "错误:用户没有登录" << endl;
    }
}

// 获取用户信息
User* UserManager::getUser(int userId) {
    if (users.find(userId) != users.end()) {
        return &users[userId];
    } else {
        cerr << "Error: User not found." << endl;
        return nullptr;
    }
}

// 简单的哈希函数（仅用于示例）
string UserManager::simpleHash(const string& input) {
    unsigned long hash = 5381; // 初始哈希值
    for (char c : input) {
        hash = ((hash << 5) + hash) + c; // hash * 33 + c
    }
    return to_string(hash);
}

// 根据用户名获取用户
User* UserManager::getUserByUsername(const std::string& username) {
    for (auto& pair : users) { // 遍历 users（假设 users 是 std::map<int, User>）
        if (pair.second.getUsername() == username) { // 检查用户名是否匹配
            return &pair.second; // 返回匹配的用户
        }
    }
    return nullptr; // 如果没有找到匹配的用户，返回 nullptr
}

bool UserManager::addUser(const std::string& username, const std::string& password, User::Role role) {
    return registerUser(username, password, role);
}

bool UserManager::deleteUser(int userId) {
    if (users.find(userId) != users.end()) {
        DatabaseManager& dbManager = DatabaseManager::getInstance();
        std::string deleteQuery = "DELETE FROM users WHERE id = " + std::to_string(userId) + ";";
        if (dbManager.executeQuery(deleteQuery)) {
            users.erase(userId);
            std::cout << "用户删除成功" << std::endl;
            return true;
        } else {
            std::cerr << "错误：用户删除失败" << std::endl;
            return false;
        }
    } else {
        std::cerr << "错误：用户未找到" << std::endl;
        return false;
    }
}

bool UserManager::updateUserRole(int userId, User::Role role) {
    if (users.find(userId) != users.end()) {
        DatabaseManager& dbManager = DatabaseManager::getInstance();
        std::string updateQuery = "UPDATE users SET role = " + std::to_string(static_cast<int>(role)) +
                                  " WHERE id = " + std::to_string(userId) + ";";
        if (dbManager.executeQuery(updateQuery)) {
            users[userId].setRole(role);
            std::cout << "用户角色更新成功" << std::endl;
            return true;
        } else {
            std::cerr << "错误：用户角色更新失败" << std::endl;
            return false;
        }
    } else {
        std::cerr << "错误：用户未找到" << std::endl;
        return false;
    }
}

// 密码验证函数
bool UserManager::verifyPassword(const string& password, const string& passwordHash) {
    string hashedPassword = simpleHash(password);
    return hashedPassword == passwordHash;
}

UserManager::~UserManager() {
    // 析构函数实现
}
